package com.learn.sqlsession.impl;

import com.learn.pojo.Configuration;
import com.learn.pojo.MappedStatement;
import com.learn.sqlsession.Executor;
import com.learn.sqlsession.SqlSession;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @author WuLiangHang
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession() {
    }

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> queryForList(String statementId, Object... args) throws SQLException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InvocationTargetException, IntrospectionException, InstantiationException {
        Executor executor = new SimpleExecutor();
        MappedStatement statement = configuration.getMap().get(statementId);
        return executor.query(configuration, statement, args);
    }

    @Override
    public <T> T queryForOne(String statementId, Object... args) throws SQLException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException, InstantiationException, IntrospectionException, InvocationTargetException {
        List<T> list = queryForList(statementId, args);
        if (list.size() == 1) {
            return list.get(0);
        } else {
            throw new RuntimeException("参数个数过多或者无查询结果！");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        return (T) Proxy.newProxyInstance(mapperClass.getClassLoader(), new
                Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //设置全限定类名和方法名获取到statementId
                String namespace = method.getDeclaringClass().getName();
                String methodName = method.getName();
                String statementId = namespace + "." + methodName;
                //获取参数 args
                //通过返回值判断调用selectOne还是selectList
                //判断是否实现泛型类型参数化
                Type genericReturnType = method.getGenericReturnType();
                if (genericReturnType instanceof ParameterizedType) {
                    return queryForList(statementId, args);
                } else {
                    return queryForOne(statementId, args);
                }
            }
        });
    }
}
